#include "ctableview.h"
#include "ctableviewstyle.h"

#include <DStyle>
#include <QTimer>
#include <QVBoxLayout>

CTableView::CTableView(QWidget *parent)
    : QTableView(parent)
    , m_delegate(nullptr)
    , m_currentHoveringRow(-1)
{

    m_delegate= new CTableViewDelegate(this);

    setItemDelegate(m_delegate);
    setShowGrid(false);
    setStyle(new CTableViewStyle);
    setMouseTracking(true);
    setAttribute(Qt::WA_Hover, true);
    setSelectionBehavior(QAbstractItemView::SelectionBehavior::SelectRows);
    verticalHeader()->setVisible(false);

    installEventFilter(this);
}

CTableView::~CTableView()
{
}

bool CTableView::eventFilter(QObject *obj, QEvent *event)
{
    if (this == obj) {
        if (QEvent::Type::HoverMove == event->type()) {
            updateCurrentHoveringRow();
        }
    }
    return QTableView::eventFilter(obj, event);
}

void CTableView::updateCurrentHoveringRow()
{
    int currentHoveringRow = -1;
    QPoint logicMousePoint = viewport()->mapFromGlobal(QCursor::pos());

    if (logicMousePoint.y() < 0) {
        currentHoveringRow = -1;
    } else {
        int yLenthIndex = 0; horizontalHeader()->height();
        for (int i = 0; i < model()->rowCount(); ++i) {
            yLenthIndex += rowHeight(i);
            if (yLenthIndex >= logicMousePoint.y()) {
                currentHoveringRow = i;
                break;
            }
        }
    }
    if (currentHoveringRow != m_currentHoveringRow) {
//        qInfo() << Q_FUNC_INFO << "mouse is in row: " << currentHoveringRow;
        m_currentHoveringRow = currentHoveringRow;
        m_delegate->setCurrentHoveringRow(m_currentHoveringRow);

        // 用于触发代理paint函数
        int rightestCol = model()->columnCount() - 1;
        Q_EMIT model()->dataChanged(model()->index(m_currentHoveringRow, 0),
                                    model()->index(m_currentHoveringRow, rightestCol), {0});
    }
}
